<?php
class PresentersController extends AppController {
	var $name = 'Presenters';
	var $uses = array('Survey', 'User');
	
  	var $paginate = array(
		'Survey' => array(
			'limit' => 25,
			'order' => array('Survey.created' => 'DESC')
		),
		'User' => array(
			'limit' => 25,
			'order' => array('User.username' => 'ASC')
		)
	);
	
	/**
	 * Displays the presenter portal home page
	 * 
	 * @return 
	 */
	function index() {
		//Get the data for my surveys and closed surveys
		$this->_my_surveys();
		$this->_closed_surveys();
		
		$this->set('searchName', '');
		$this->set('searchUUID', '');
		$this->set('searchType', '');
	}
	
	/**
	 * Get the top five surveys this user has created
	 * 
	 * @return 
	 */
	function _my_surveys() {
		// Get the current user
		$active_user = $this->Auth->user();
		$userId = $active_user['User']['id'];
		
		//Get all the surveys created by this user
		$my_surveys = $this->Survey->find('all',
			array(
				'conditions' => array('Survey.isDeleted' => 0, 'Survey.created_by' => $userId),
				'fields' => array('Survey.id', 'Survey.name'),
				'order' => array('Survey.created DESC'),
				'limit' => 5,
				'recursive' => -1 //Only get survey data
		));
		
		$this->set('my_surveys', $my_surveys);
	}
	
	/**
	 * Get the top five surveys of type closed that this user has created
	 * 
	 * @return 
	 */
	function _closed_surveys() {
		// Get the current user
		$active_user = $this->Auth->user();
		$userId = $active_user['User']['id'];
		
		//Get the top 5 surveys of type 'Closed', for this user
		$closed_surveys = $this->Survey->find('all',
			array(
				'conditions' => array('Survey.isDeleted' => 0, 'SurveyType.type' => 'Closed',
				 'Survey.created_by' => $userId), //Closed surveys
				'fields' => array('Survey.id', 'Survey.name'),
				'order' => array('Survey.created DESC'),
				'limit' => 5
		));
		
		// Pass them on to the view.
		$this->set('closed_surveys', $closed_surveys);
	}
	
	/**
	 * Show the group results page for the given survey
	 * 
	 * @param object $survey_id
	 * @return 
	 */
	function show_survey_results($survey_id) {
		$this->loadModel('Question');
		$this->Question->Behaviors->attach('Containable');
		$this->Question->bindModel(array('hasOne' => array('QuestionsSurvey')));
		$questions = $this->Question->find('all', array(
			'conditions' => array('QuestionsSurvey.survey_id' => $survey_id, 'Question.isDeleted' => 0),
			'order' => array('Question.viewOrder ASC'),
			'contain' => array('QuestionsSurvey')
		));

		$i = 0;
		foreach($questions as $question) {
			$questions_surveys_id[] = $question['QuestionsSurvey']['id'];
			
			$this->loadModel('Answer');
			$this->Answer->Behaviors->attach('Containable');
			$answers[] = $this->Answer->find('all', array(
				'conditions' => array(
					'Answer.question_id' => $question['Question']['id'],
					'Answer.isDeleted' => 0
				),
				'order' => array('Answer.viewOrder ASC')
			));
			
			foreach($answers[$i] as $answer) {
				$this->loadModel('Response');
				$this->Response->Behaviors->attach('Containable');
				$response_counts[$i][] = $this->Response->find('count', array(
					'conditions' => array(
						'Response.questions_surveys_id' => $question['QuestionsSurvey']['id'],
						'Response.answer_id' => $answer['Answer']['id']
					)
				));
			}
			$i++;
		}
		
		$this->set('questions', $questions);
		$this->set('answers', $answers);
		$this->set('response_counts', $response_counts);
	}
	
	/**
	 * Search audience members
	 * 
	 * @return 
	 */
	function search_audience() {
		//Flag whether or not to display results
		$this->set('display', false);
	    
		//Get the search term either from the post data or the session 
	    if(!empty($this->data))
		{
	        $searchName = trim($this->data['User']['username']);
			$searchFName = trim($this->data['User']['firstname']);
			$searchLName = trim($this->data['User']['lastname']);
			$searchEmail = trim($this->data['User']['email']);
		}
		elseif($this->Session->check($this->name.'.searchIndName') ||
		 $this->Session->check($this->name.'.searchIndFirstName') || 
		 $this->Session->check($this->name.'.searchIndLastName') || 
		 $this->Session->check($this->name.'.searchIndEmail'))
		{
			if($this->Session->check($this->name.'.searchIndName'))
	        	$searchName = $this->Session->read($this->name.'.searchIndName');
			if($this->Session->check($this->name.'.searchIndFirstName'))
	        	$searchFName = $this->Session->read($this->name.'.searchIndFirstName');
			if($this->Session->check($this->name.'.searchIndLastName'))
	        	$searchFName = $this->Session->read($this->name.'.searchIndLastName');
			if($this->Session->check($this->name.'.searchIndEmail'))
	        	$searchFName = $this->Session->read($this->name.'.searchIndEmail');
		}
	
	    $filters = array();
		$this->set('searchUsername', '');
		$this->set('searchFirstname', '');
		$this->set('searchLastname', '');
		$this->set('searchEmail', '');
		
	    if(isset($searchName)) {
	    	//Set up the search filters
	        $filters = array('lower(User.username) LIKE' => '%'.low($searchName).'%');
	        $this->Session->write($this->name.'.searchIndName', $searchName);
			$this->set('searchName', $searchName);
			$this->set('display', true);
	    }
		
		if(isset($searchFName)) {
	    	//Set up the search filters
			$key = 'lower(User.firstname) LIKE';
			$value = '%'.low($searchFName).'%';
			$fNameFilters = array($key=>$value);
			$filters = array_merge($filters, $fNameFilters);
			
	        $this->Session->write($this->name.'.searchIndFirstName', $searchFName);
			$this->set('searchFName', $searchFName);
			$this->set('display', true);
	    }
		
		if(isset($searchLName)) {
	    	//Set up the search filters
			$key = 'lower(User.lastname) LIKE';
			$value = '%'.low($searchLName).'%';
			$lNameFilters = array($key=>$value);
			$filters = array_merge($filters, $lNameFilters);
			
	        $this->Session->write($this->name.'.searchIndLastName', $searchLName);
			$this->set('searchLName', $searchLName);
			$this->set('display', true);
	    }
		
		if(isset($searchEmail)) {
	    	//Set up the search filters
			$key = 'lower(User.email) LIKE';
			$value = '%'.low($searchEmail).'%';
			$emailFilters = array($key=>$value);
			$filters = array_merge($filters, $emailFilters);
			
	        $this->Session->write($this->name.'.searchIndEmail', $searchEmail);
			$this->set('searchEmail', $searchEmail);
			$this->set('display', true);
	    }
		
		$key = 'LENGTH(username) != ';
		$value = "0";
		$emailFilters = array($key=>$value);
		$filters = array_merge($filters, $emailFilters);
		
		$users = $this->paginate('User', $filters);
	    $this->set('users', $users);
	}
	
	function group_results() {
		$this->_getSurveys();
	}
	
	/**
	 * Search for surveys by name and unique id
	 * 
	 * @return 
	 */
	function _getSurveys() {
		//Flag whether or not to display results
		$this->set('display', false);
		
		$searchName = "";
		$searchUUID = "";
		$searchType = "";
	    
		//Get the search term either from the post data or the session 
	    if(!empty($this->data))
		{
	        $searchName = trim($this->data['Survey']['name']);
			$searchUUID = trim($this->data['Survey']['uuid']);
			$searchType = trim($this->data['SurveyType']['type']);
		}
		elseif($this->Session->check($this->name.'.searchPreName') || $this->Session->check($this->name.'.searchPreUUID')
				|| $this->Session->check($this->name.'.searchPreType'))
		{
			if($this->Session->check($this->name.'.searchPreName'))
	        	$searchName = $this->Session->read($this->name.'.searchPreName');
			if($this->Session->check($this->name.'.searchPreUUID'))
	        	$searchUUID = $this->Session->read($this->name.'.searchPreUUID');
			if($this->Session->check($this->name.'.searchPreType'))
	        	$searchType = $this->Session->read($this->name.'.searchPreType');
		}
	
	    $filters = array();
		$this->set('searchName', '');
		$this->set('searchUUID', '');
		$this->set('searchType', '');
		
	    if(!empty($searchName)) {
	    	//Set up the search filters
	        $filters = array('lower(Survey.name) LIKE' => '%'.low($searchName).'%', 'Survey.isDeleted' => '0');
	        $this->Session->write($this->name.'.searchPreName', $searchName);
			$this->set('searchName', $searchName);
			$this->set('display', true);
	    }
		
		if(!empty($searchUUID)) {
	    	//Set up the search filters
			$key = 'SUBSTRING(Survey.uuid,2,8) LIKE';
			$value = '%'.$searchUUID.'%';
			$uuidFilters = array($key=>$value);
			$filters = array_merge($filters, $uuidFilters);
			
	        $this->Session->write($this->name.'.searchPreUUID', $searchUUID);
			$this->set('searchUUID', $searchUUID);
			$this->set('display', true);
	    }
		
		if(!empty($searchType)) {
	    	//Set up the search filters
			$key = 'SurveyType.type';
			$value = $searchType;
			$typeFilters = array($key=>$value);
			$filters = array_merge($filters, $typeFilters);
			
	        $this->Session->write($this->name.'.searchPreType', $searchType);
			$this->set('searchType', $searchType);
			$this->set('display', true);
	    }
		
		$surveys = array();
		// Get the current user
		$active_user = $this->Auth->user();
		$userId = $active_user['User']['id'];
		
		if(!empty($filters)) {
			//Filter by user
			$key = 'Survey.created_by';
			$value = $userId;
			$userFilters = array($key=>$value);
			$filters = array_merge($filters, $userFilters);
		} else {
			$filters = array('Survey.created_by' => $userId);
		}
		
		$surveys = $this->paginate('Survey', $filters);
	    $this->set('surveys', $surveys);
	}
}
?>
